package main

import (
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

/**
handler包可以处理不同的二级域名,他先根据域名获取对应的handler路由，然后调用处理
*/

type HostMap map[string]http.Handler

func (h HostMap) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	//先根据域名获取对应的Handler路由 然后调用处理（分发机制）
	if handler := h[request.Host]; handler != nil {
		handler.ServeHTTP(writer, request)
	} else {
		http.Error(writer, "Forbidden", 403)
	}

}

func main() {
	userRouter := httprouter.New()
	userRouter.GET("/", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
		writer.Write([]byte("sub1"))
	})

	dataRouter := httprouter.New()
	dataRouter.GET("/", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
		writer.Write([]byte("sub2"))
	})

	hostMap := make(HostMap)
	hostMap["sub1.localhost:8888"] = userRouter
	hostMap["sub2.localhost:8888"] = dataRouter
	log.Fatal(http.ListenAndServe(":8888", hostMap))
}
